﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SQLite;

namespace festivalDatabase
{
    public partial class editMusician : userInterface
    {
        string oldMusicianName;

        public editMusician(dbAccessor db, festivalTypes type, int festivalID)
        {
            InitializeComponent();
            setIcon();
            dbAccess = db;
            currentFestivalID = festivalID;
            currentFestivalType = type;
            setIcon();
            updateMusicianList();
            addMusicianRadio.Checked = true;
        }

        /// <summary>
        /// Updates the musicianListBox to reflect the database.
        /// </summary>
        /// <param name="festID"></param>
        public void updateMusicianList()
        {
            musicianListBox.Items.Clear();

            SQLiteCommand query = dbAccess.getCommand();

            query.CommandText = "SELECT musician_name " +
                                "FROM musician;";

            try
            {
                DataTable dt = dbAccess.executeQuery(query);

                foreach (DataRow row in dt.Rows)
               {
                    musicianListBox.Items.Add(row["musician_name"].ToString());
               }
            }
            catch
            {
                // do nothing
            }
        }

        /// <summary>
        /// Detects when anything in the musicianListBox changes.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void musicianListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            oldMusicianName = musicianListBox.SelectedItem.ToString();

            SQLiteCommand query = dbAccess.getCommand();

            query.CommandText = "SELECT musician_name, performance_fee, genre, telephone_number " +
                                "FROM musician " +
                                "WHERE musician_name=@name;";
            SQLiteParameter param = new SQLiteParameter("@name", musicianListBox.SelectedItem.ToString());
            query.Parameters.Add(param);

            try
            {
                festivals = dbAccess.executeQuery(query);
                {
                    DataRow row = festivals.Rows[0];
                    musicianNameTextBox.Text = (string)(row["musician_name"].ToString());
                    maskedmusicianTelephoneTextBox.Text = (string)(row["telephone_number"].ToString());
                    musicianFeeTextBox.Text = (string)(row["performance_fee"].ToString());
                    musicianGenreTextBox.Text = (string)(row["genre"].ToString());
                }
            }
            catch
            {
                // do nothing
            }
        }

        /// <summary>
        /// Detects when the submit button is clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void submitButton_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (addMusicianRadio.Checked)
                addMusician();
            else if (editMusicianInfoRadioButton.Checked)
                editMusicianInfo();
            else
                removeMusician();
        }

        /// <summary>
        /// Adds a musician to the database. 
        /// </summary>
        private void addMusician()
        {
            if (musicianNameTextBox.Text != "" && musicianNameIsUnique())
            {
                if (validNumLength(maskedmusicianTelephoneTextBox.Text.ToString(), 10, true))
                {
                    if (validFeeAmount(musicianFeeTextBox.Text) || musicianFeeTextBox.Text == "")
                    {

                        SQLiteCommand nonQuery = dbAccess.getCommand();

                        //INSERTS the new musician into the dB
                        nonQuery.CommandText = "INSERT INTO musician (musician_name";
                        
                        if (validNumLength(maskedmusicianTelephoneTextBox.Text.ToString(), 10, false))
                            nonQuery.CommandText += ", telephone_number";
                        if (validFeeAmount(musicianFeeTextBox.Text.ToString()))
                            nonQuery.CommandText += ", performance_fee";
                        if (musicianGenreTextBox.Text.Length > 0)
                            nonQuery.CommandText += ", genre";

                        nonQuery.CommandText += ") VALUES (@Mus";
                        SQLiteParameter param = new SQLiteParameter("@Mus", musicianNameTextBox.Text.ToString());
                        nonQuery.Parameters.Add(param);

                        if (validNumLength(maskedmusicianTelephoneTextBox.Text.ToString(), 10, false))
                        {
                            nonQuery.CommandText += ", @Phone";
                            param = new SQLiteParameter("@Phone", maskedmusicianTelephoneTextBox.Text.ToString());
                            nonQuery.Parameters.Add(param);
                        }
                        if (validFeeAmount(musicianFeeTextBox.Text.ToString()))
                        {
                            nonQuery.CommandText += ", @Fee";
                            param = new SQLiteParameter("@Fee", Int32.Parse(musicianFeeTextBox.Text.ToString()));
                            nonQuery.Parameters.Add(param);
                        }
                        if (musicianGenreTextBox.Text.Length > 0)
                        {
                            param = new SQLiteParameter("@Genre", musicianGenreTextBox.Text.ToString());
                            nonQuery.Parameters.Add(param);
                        }
                        nonQuery.CommandText += ");";
                        dbAccess.executeNonQuery(nonQuery);
                        MessageBox.Show("Musician added successfully.");
                        updateMusicianList();
                        musicianNameTextBox.Text = "";
                        maskedmusicianTelephoneTextBox.Text = "";
                        musicianFeeTextBox.Text = "";
                        musicianGenreTextBox.Text = "";
                    }
                    else
                        errorProvider1.SetError(musicianFeeTextBox, "Invalid fee amount");
                }
                else
                    errorProvider1.SetError(maskedmusicianTelephoneTextBox, "Invalid phone number");
            }
            else
                errorProvider1.SetError(musicianNameTextBox, "Please enter a unique musician name");
        }

        /// <summary>
        /// Determines whether a given fee is valid or not.
        /// </summary>
        /// <param name="feeToCheck"></param>
        /// <returns></returns>
        bool validFeeAmount(String feeToCheck)
        {
            try
            {
                Int32.Parse(feeToCheck);
            }
            catch
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// Changes the musician's information based on the textboxes.
        /// </summary>
        private void editMusicianInfo()
        {
            if ((musicianNameIsUnique() == true) || (musicianNameTextBox.Text.ToString() == oldMusicianName))
            {
                if (validNumLength(maskedmusicianTelephoneTextBox.Text.ToString(), 10, true))
                {
                    if (validFeeAmount(musicianFeeTextBox.Text) || musicianFeeTextBox.Text == "")
                    {
                        //UPDATES musician with the new information
                        SQLiteCommand nonQuery = dbAccess.getCommand();
                        nonQuery.CommandText = "UPDATE musician SET " +
                                               "musician_name=@mus";
                        nonQuery.Parameters.Add("@mus", DbType.String);
                        nonQuery.Parameters["@mus"].Value = musicianNameTextBox.Text.ToString();

                        if (validFeeAmount(musicianFeeTextBox.Text))
                        {
                            nonQuery.CommandText += ", performance_fee=@fee";
                            nonQuery.Parameters.Add("@fee", DbType.Int32);
                            nonQuery.Parameters["@fee"].Value = Int32.Parse(musicianFeeTextBox.Text.ToString());
                        }
                        nonQuery.CommandText += ", genre=@genre";
                        nonQuery.Parameters.Add("@genre", DbType.String);
                        nonQuery.Parameters["@genre"].Value = musicianGenreTextBox.Text.ToString();
                        nonQuery.CommandText += ", telephone_number=@phone";
                        nonQuery.Parameters.Add("@phone", DbType.String);
                        nonQuery.Parameters["@phone"].Value = maskedmusicianTelephoneTextBox.Text.ToString();
                        nonQuery.CommandText += " WHERE musician_name=@oldName;";
                        nonQuery.Parameters.Add("@oldName", DbType.String);
                        nonQuery.Parameters["@oldName"].Value = oldMusicianName;
                        dbAccess.executeNonQuery(nonQuery);

                        nonQuery = dbAccess.getCommand();
                        nonQuery.CommandText = "UPDATE musician_plays " +
                                               "SET musician_name=@name " +
                                               "WHERE musician_name=@oldName;";
                        SQLiteParameter param = new SQLiteParameter("@name", musicianNameTextBox.Text.ToString());
                        nonQuery.Parameters.Add(param);
                        param = new SQLiteParameter("@oldName", oldMusicianName);
                        nonQuery.Parameters.Add(param);
                        dbAccess.executeNonQuery(nonQuery);

                        updateMusicianList();
                        musicianNameTextBox.Text = "";
                        maskedmusicianTelephoneTextBox.Text = "";
                        musicianFeeTextBox.Text = "";
                        musicianGenreTextBox.Text = "";
                        MessageBox.Show("Musician edited successfully");
                    }
                    else
                        errorProvider1.SetError(musicianFeeTextBox, "Invalid fee amount");
                }
                else
                    errorProvider1.SetError(maskedmusicianTelephoneTextBox, "Invalid phone number");
            }
            else
                errorProvider1.SetError(musicianNameTextBox, "Please enter a unique musician name");
        }

        /// <summary>
        /// Deletes a musician from the database.
        /// </summary>
        private void removeMusician()
        {
            SQLiteCommand nonQuery = dbAccess.getCommand();

            // Deletes musician from musician table
            nonQuery.CommandText = "DELETE " +
                                   "FROM musician " +
                                   "WHERE musician_name=@Mus;";
            nonQuery.Parameters.Add("@Mus", DbType.String);
            nonQuery.Parameters["@Mus"].Value = musicianNameTextBox.Text.ToString();
            dbAccess.executeNonQuery(nonQuery);

            nonQuery = dbAccess.getCommand();
            nonQuery.CommandText = "DELETE FROM musician_plays " +
                                   "WHERE musician_name=@Mus;";
            nonQuery.Parameters.Add("@Mus", DbType.String);
            nonQuery.Parameters["@Mus"].Value = musicianNameTextBox.Text.ToString();
            dbAccess.executeNonQuery(nonQuery);

            updateMusicianList();
            musicianNameTextBox.Text = "";
            maskedmusicianTelephoneTextBox.Text = "";
            musicianFeeTextBox.Text = "";
            musicianGenreTextBox.Text = "";
            MessageBox.Show("Musician deleted");
        }

        /// <summary>
        /// Checks to see whether the edit radio button is clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void editMusicianInfoRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            musicianNameTextBox.Text = "";
            musicianNameTextBox.Enabled = true;
            maskedmusicianTelephoneTextBox.Text = "";
            maskedmusicianTelephoneTextBox.Enabled = true;
            musicianFeeTextBox.Text = "";
            musicianFeeTextBox.Enabled = true;
            musicianGenreTextBox.Text = "";
            musicianGenreTextBox.Enabled = true;
            musicianListBox.Enabled = true;
            submitButton.Text = "Edit Musician";
        }

        /// <summary>
        /// Checks to see if the remove radio button is selected.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void removeMusicianRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            musicianNameTextBox.Text = "";
            musicianNameTextBox.Enabled = false;
            maskedmusicianTelephoneTextBox.Text = "";
            maskedmusicianTelephoneTextBox.Enabled = false;
            musicianFeeTextBox.Text = "";
            musicianFeeTextBox.Enabled = false;
            musicianGenreTextBox.Text = "";
            musicianGenreTextBox.Enabled = false;
            musicianListBox.Enabled = true;
            submitButton.Text = "Remove Musician";
        }


        private void addMusicianRadio_CheckedChanged(object sender, EventArgs e)
        {
            musicianNameTextBox.Text = "";
            musicianNameTextBox.Enabled = true;
            maskedmusicianTelephoneTextBox.Text = "";
            maskedmusicianTelephoneTextBox.Enabled = true;
            musicianFeeTextBox.Text = "";
            musicianFeeTextBox.Enabled = true;
            musicianGenreTextBox.Text = "";
            musicianGenreTextBox.Enabled = true;
            musicianListBox.Enabled = false;
            submitButton.Text = "Add Musician";
        }

        private bool musicianNameIsUnique()
        {
            SQLiteCommand query = dbAccess.getCommand();
            query.CommandText = "SELECT musician_name FROM musician;";
            DataTable dt = dbAccess.executeQuery(query);

            try
            {
                foreach (DataRow row in dt.Rows)
                {
                    if (row["musician_name"].ToString() == musicianNameTextBox.Text.ToString())
                        return false;
                }
            }
            catch
            {
                return true;
            }

            return true;
        }
    }
}


